<template>
  <div class="SystemMessage">
    <el-radio-group v-model="type" fill="#7b94d8" @change="search">
      <el-radio-button label="3">新增消息</el-radio-button>
      <el-radio-button label="1">未发送</el-radio-button>
      <el-radio-button label="2">已发送</el-radio-button>
      <!-- <el-radio-button label="3">结算记录</el-radio-button> -->
    </el-radio-group>
    <el-card>
      <el-form
        v-show="type == 3"
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="用户选择" prop="type">
          <el-radio-group v-model="form.screen_type" @change="rulesChange">
            <el-radio label="1">选择用户类型</el-radio>
            <el-radio label="2">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="form.screen_type == 2"
          label="用户ID"
          prop="userId"
        >
          <el-input
            style="width: 500px"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="form.userId"
          ></el-input>
          <upload-excel-component
            class="drop1"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          />
          多个用户id请用英文逗号隔开
        </el-form-item>
        <el-form-item
          label="用户类型选择"
          v-show="form.screen_type == 1"
          prop="userType"
        >
          <el-checkbox-group v-model="form.userType">
            <el-checkbox label="1">注册用户</el-checkbox>
            <el-checkbox label="2">认证用户</el-checkbox>
            <el-checkbox label="3">工会认证用户</el-checkbox>
            <el-checkbox label="4">平台认证用户</el-checkbox>
          </el-checkbox-group>
          <!-- <el-input v-model="form.userType"></el-input> -->
        </el-form-item>
        <el-form-item
          label="用户性别选择"
          v-show="form.screen_type == 1"
          prop="userSex"
        >
          <el-radio-group v-model="form.userSex">
            <el-radio label="1">男用户</el-radio>
            <el-radio label="2">女用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户精准类型选择"
          v-show="form.screen_type == 1"
          prop="user_accurate_type"
        >
          <el-radio-group v-model="form.user_accurate_type">
            <el-radio label="1">3日未登录</el-radio>
            <el-radio label="2">5日未登录</el-radio>
            <el-radio label="3">7日未登录</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发送方式" prop="sendType">
          <el-radio-group v-model="form.sendType" @change="form.img = ''">
            <el-radio label="1">个推</el-radio>
            <el-radio label="2">系统消息</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主标题" prop="title">
          <el-input
            v-model="form.title"
            maxlength="20"
            clearable
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="45"
            type="textarea"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" v-show="form.sendType == 2" prop="img">
          <el-upload
            class="avatar-uploader upLoadBox"
            :http-request="upLoad"
            :show-file-list="false"
            action
          >
            <img v-if="form.img" :src="form.img" class="img" />
            <i v-else class="el-icon-plus avatar-uploader-icon img"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="时间选择" prop="timeType">
          <el-radio-group v-model="form.timeType" @change="form.pushTime = ''">
            <el-radio label="1">立即发送</el-radio>
            <el-radio label="2">指定时间发送</el-radio>
          </el-radio-group>
          <el-date-picker
            :disabled="form.timeType == 1"
            size="small"
            style="margin-left: 20px"
            v-model="form.pushTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" clearable></el-input>
        </el-form-item>
        <el-button class="btn" @click="submit">提 交</el-button>
        <el-button @click="reset">重 置</el-button>
      </el-form>
      <div v-show="type != 3">
        <div class="searchBox">
          <el-input placeholder="请输入内容" v-model="id">
            <template slot="prepend">ID</template>
          </el-input>
          <el-input placeholder="请输入内容" v-model="title">
            <template slot="prepend">标题</template>
          </el-input>
          <el-date-picker
            v-model="timeArr"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="timeOptions"
            value-format="yyyy-MM-dd"
            @change="focusA"
          >
          </el-date-picker>
          <el-button style="margin-left: 10px" class="btn" @click="search"
            >搜索</el-button
          >
        </div>
        <el-table
          :data="tableData"
          style="width: 100%; margin-top: 10px"
          :header-cell-style="{ background: '#f5f7fa' }"
          v-loading="loading"
        >
          <template slot="empty">
            <el-empty :image-size="200"></el-empty>
          </template>
          <el-table-column prop="id" label="ID"> </el-table-column>
          <el-table-column prop="creationTime" label="推送时间">
            <template slot-scope="scope">
              {{ scope.row.creationTime | time }}
            </template>
          </el-table-column>
          <el-table-column prop="screen_type" label="推送目标">
            <template slot-scope="scope">
              {{ scope.row.screen_type == 1 ? "按用户类型" : "指定用户" }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="userSex" label="推送性别"> </el-table-column> -->
          <el-table-column prop="send_type" label="推送类型">
            <template slot-scope="scope">
              {{ scope.row.send_type == 1 ? "个推" : "系统消息" }}
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题"> </el-table-column>
          <el-table-column prop="content" label="正文"> </el-table-column>
          <el-table-column prop="img" label="图片">
            <template slot-scope="scope">
              <div v-if="scope.row.img">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.img"
                  :preview-src-list="[scope.row.img]"
                >
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="img" label="操作" width="300">
            <template slot-scope="scope">
              <el-button
                v-if="type == 1"
                type="info"
                plain
                size="small"
                @click="operation(scope.row.id, '1')"
                >撤回</el-button
              >
              <el-button
                size="small"
                type="primary"
                plain
                @click="edit(scope.row)"
                >{{ type == 1 ? "编辑" : "再次发送" }}</el-button
              >
              <el-button
                v-if="type == 1"
                type="success"
                plain
                size="small"
                @click="operation(scope.row.id, '2')"
                >立即发送</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="total"
          :page.sync="page"
          :limit.sync="pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import UploadExcelComponent from "@/components/UploadExcel/index.vue";
import { client } from "@/utils/oss.js";
import {
  ossToken,
  // noticeMessagePush,
  noticeList,
  noticeMessageOperation,
  noticeMessageAdd, //系统消息新增
} from "@/api/NotificationManagement";
import moment from "moment";
export default {
  components: { Pagination, UploadExcelComponent },
  data() {
    return {
      type: "3",
      loading: false,
      form: {
        id: "",
        screen_type: "",
        userId: "",
        userType: [],
        userSex: "",
        user_accurate_type: "",
        sendType: "1",
        title: "",
        content: "",
        img: "",
        timeType: "1",
        pushTime: "",
        url: "",
      },
      rules: {
        screen_type: [{ required: true, message: "请选择", trigger: "change" }],
        content: [{ required: true, message: "请输入", trigger: "change" }],
      },
      //列表
      id: "",
      title: "",
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      timeArr: [],
      startDate: "",
      endDate: "",
      timeOptions: {
        disabledDate(platformValue) {
          return platformValue.getTime() > Date.now() - 8.64e6;
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  methods: {
    //选着时间
    focusA(time) {
      if (!this.timeArr) {
        this.timeArr = [];
      }
      this.startDate = this.timeArr[0];
      this.endDate = this.timeArr[1];
    },
    submit() {
      console.log(this.form);
      // noticeMessageAdd
      this.$refs.form.validate().then(async () => {
        let obj = JSON.parse(JSON.stringify(this.form));
        obj.userType = obj.userType.join(",");
        const res = await noticeMessageAdd(obj);
        if (res.code == 0) {
          this.$message.success("提交成功！");
          this.$refs.form.resetFields();
          this.form.pushTime = "";
        }
      });
    },
    rulesChange(type) {
      let userType = [
        {
          required: true,
          message: "请至少选择一个",
          trigger: "change",
        },
      ];
      let userId = [
        { required: true, message: "请输入用户id", trigger: "change" },
      ];
      if (type == 1) {
        this.rules = { ...this.rules, userType };
        this.rules.userId = [];
      }
      if (type == 2) {
        this.rules = { ...this.rules, userId };
        this.rules.userType = [];
      }
    },
    handleSuccess({ results, header }) {
      let arr = [...header];
      console.log("结果", results, header);
      results.forEach((item) => {
        arr.push(...Object.values(item));
      });
      this.form.userId = arr.join(",");
    },
    //导入表格
    beforeUpload(file) {
      return true;
    },
    async upLoad(file, obj) {
      //   console.log(obj);
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      try {
        let fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        //fileNames上传文件的名称
        //file.file上传文件的内容
        let cli = client(this.dataObj);
        let result = cli.multipartUpload(fileNames, file.file);
        result.then(() => {
          self.form.img = "https://img.psychexy.com" + fileNames;
          self.$message({
            message: "上传成功",
            type: "success",
          });
        });
      } catch (e) {
        self.$message.error("上传失败");
      }
    },
    //列表请求
    async getList() {
      //   this.loading = true;
      let status = 0;
      if (this.type == 1) {
        status = 0;
      } else if (this.type == 2) {
        status = 1;
      }

      const res = await noticeList({
        id: this.id,
        title: this.title,
        page: this.page,
        pageSize: this.pageSize,
        startTime: this.startDate,
        endTime: this.endDate,
        status,
      });
      this.loading = false;
      if (res.code == 0) {
        this.total = parseInt(res.data.count);
        this.tableData = res.data.list;
        this.tableData.forEach((item) => {
          item.creationTime = item.creationTime * 1000;
        });
      }
    },
    search() {
      if (this.type == 3) return;
      this.page = 1;
      this.getList();
    },
    //撤回与发送
    operation(id, type) {
      this.$confirm(`是否${type == 1 ? "撤回消息" : "立即发送"}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await noticeMessageOperation({
            id,
            type,
          });
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.getList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //编辑
    edit(obj) {
      this.form.screen_type = obj.screen_type;
      // this.form.userId
      this.form.userType = obj.user_type.split(",");
      this.form.userSex = obj.user_sex;
      this.form.user_accurate_type = obj.user_accurate_type;
      this.form.sendType = obj.send_type;
      this.form.title = obj.title;
      this.form.content = obj.content;
      this.form.img = obj.img;
      this.form.timeType = "2";
      this.form.pushTime = obj.creationTime;
      this.form.url = obj.url;
      this.type = "3";
    },
    reset() {
      this.$refs.form.resetFields();
      this.form.pushTime = "";
      // this.form = {
      //   id: "",
      //   screen_type: "",
      //   userId: "",
      //   userType: [],
      //   userSex: "",
      //   user_accurate_type: "",
      //   sendType: "1",
      //   title: "",
      //   content: "",
      //   img: "",
      //   timeType: "1",
      //   pushTime: "",
      //   url: "",
      // };
    },
  },
  filters: {
    time(value) {
      return moment(value).format("YYYY-MM-DD hh:mm:ss");
    },
  },
};
</script>

<style lang="less" scoped>
.SystemMessage {
  padding: 20px;
  .drop1 {
    display: inline-block;
  }
  .el-icon-plus {
    text-align: center;
    line-height: 200px;
    width: 200px;
    box-sizing: border-box;
    height: 200px;
    border: 1px dashed #ccc;
  }
  .img {
    width: 190px;
    height: 190px;
  }
  .searchBox {
    .el-input {
      width: 300px;
      margin-right: 10px;
    }
  }
}
</style>